'''
Created on Mar 7, 2016

@author: JimmyMo
'''
from reader.reader import Reader
import json
import time
from database import dao
import threading
import traceback
import sys

class RedisReader(Reader):
    def _parse_options(self, raw_options):
        self.host = "localhost" 
        self.port = 6379
        self.c_db = 0
        self.p_db = 1
        self.group = "BBB"
        self.buffer_size = 200000
        self.t_name = "redis_t"
#         self.key = "h1"
        pass
    def __init__(self, queue, raw_options):
        super().__init__(queue, raw_options)
        self.data = queue
        self.rc_client = dao.get_redis_connection(self.host, self.port, self.c_db)
        self.rp_client = dao.get_redis_connection(self.host, self.port, self.p_db)
        pass
    def run(self):
        try:
            counter = 0;
            now = time.clock()
            cursor = 0
            started = False
            while cursor > 0 or not started:
                started = True
#                 b = self.rc_client.scan(cursor, count=self.buffer_size)
                b = self.rc_client.scan(cursor, ("msg:c:*"), count=self.buffer_size)
#                 b = self.rc_client.scan(cursor, ("GRP:%s*" % self.group), count=self.buffer_size)
                cursor = b[0]
                keys = b[1]
                if keys:
                    current_event_bytes = self.rc_client.mget(keys)
                    for e in current_event_bytes:
                        counter = counter + 1
                        self.data.put(e)
                print("counter is %d..." % counter)
                print("there is %d data in queue..." % self.data._qsize())
            
            self.data.put("_produced_end")
        except Exception as e:
            print("Printing only the traceback above the current stack frame")
            print("".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])))
            print("Printing the full traceback as if we had not caught it here...")
            print(RedisReader.format_exception(e))
#                 prior_event_bytes = self.rp_client.mget(keys)
    @staticmethod
    def format_exception(e):
        exception_list = traceback.format_stack()
        exception_list = exception_list[:-2]
        exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
        exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))
    
        exception_str = "Traceback (most recent call last):\n"
        exception_str += "".join(exception_list)
        # Removing the last \n
        exception_str = exception_str[:-1]

        return exception_str           